package band.wukong.practice.netty.definitiveguide2nd.ch0304;

import band.wukong.practice.netty.Env;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Desc: 粘包拆包异常案例
 * author: wukonggg@139.com
 */
public class TimeClientChannelHandler2 extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LogManager.getLogger();

    private int counter;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
        ByteBuf msg = null;
        for (int i = 0; i < 100; i++) {
            msg = Unpooled.buffer(req.length);
            msg.writeBytes(req);
            ctx.writeAndFlush(msg);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, Env.ENCODE);
        logger.info("Now is: " + body);
        logger.info("The counter is: " + ++counter);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close().sync();   //完成一次tcp访问后就关闭Channel
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}
